package com.zhuoyue;

import com.zhuoyue.biz.core.api.domain.AppUserDO;
import com.zhuoyue.biz.core.api.domain.GatewayDO;
import com.zhuoyue.biz.core.api.service.AppUserService;
import com.zhuoyue.biz.core.api.service.GatewayService;
import com.zhuoyue.biz.core.command.cmd.common.CmdUtil;
import com.zhuoyue.common.api.XmlParse;
import com.zhuoyue.common.jwt.util.JwtOperator;
import com.zhuoyue.common.utils.CmdUtils;
import com.zhuoyue.common.utils.Md5;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.util.jar.Attributes;

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class AppUserController {
    @Autowired
    private AppUserService appUserService;

    @Autowired
    private JwtOperator jwtOperator;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private GatewayService gatewayService;


    /**
     * @Description:登录测试
     * @author wjming
     * @Date 2021/2/20 12:40
     */
    @Test
    public void LogTest() throws Exception {
        AppUserDO appUserDO = new AppUserDO();
        appUserDO.setAccount("13868923544");
        appUserDO.setPassword("123456");
        appUserDO.setOrganizationCode("zyzn");
        AppUserDO appUserByAccountAndPassword = appUserService.getAppUserByAccountAndPassword(appUserDO);
        if (appUserByAccountAndPassword != null) {
            // 为本次登录生成新的token
            Map<String, Object> claims = new HashMap<>(6);
            claims.put("id", appUserByAccountAndPassword.getId());
            claims.put("account", appUserByAccountAndPassword.getAccount());
            claims.put("orgCode", appUserByAccountAndPassword.getOrganizationCode());
            claims.put("sourceId", appUserByAccountAndPassword.getSourceId());
            claims.put("sourceType", appUserByAccountAndPassword.getSourceType());
            String token = jwtOperator.generateToken(claims);
            System.out.println("token = " + token);
        }
    }

    /**
     * @Description:用户信息查询测试
     * @author wjming
     * @Date 2021/2/20 12:41
     */
    @Test
    public void getUserMessageTest() {
        AppUserDO appUserDO = appUserService.getById("002ededb899854c242e7184f69369950");
    }

    @Test
    public void addUserMssageTest() throws Exception {
        AppUserDO appUserDO = new AppUserDO();
        appUserDO.setAccount("15000000000");
        appUserDO.setPassword(new Md5().getMd5("1234567890"));
        appUserDO.setType("1");
        appUserDO.setNickName("我又当舅舅了");
        appUserDO.setImgUrl("000000");
        appUserDO.setTsbz("1");
    }

    @Test
    public void JwtOperator() throws Exception {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ImJjMDQzZDc4YzBjZDI3MGUyYWI0M2ZjZGI2NzAyZjVjIiwidHlwZSI6InZvaWNlIiwiYWNjb3VudCI6IjEzMTE2NzQyMDg2Iiwib3JnQ29kZSI6Inp5em4iLCJpYXQiOjE2MTY3Mzk3OTEsImV4cCI6MTYxNzk0OTM5MX0.yL8wjMxAJ58OppLFOzySGbEGacB6xtdb-pGy_Al8NBA";
        Boolean aBoolean = jwtOperator.validateToken(token);
        System.out.println("aBoolean = " + aBoolean);
        Claims claimsFromToken = jwtOperator.getClaimsFromToken(token);
        System.out.println("claimsFromToken.getId() = " + claimsFromToken.get("id").toString());
    }

    @Test
    public void JwtOperatorJm() throws Exception {
        Map<String, Object> map = new HashMap<>(2);
        map.put("id", "f5b37b085b87935c472da45cff5ae255");
        map.put("orgCode", "zyzn");
        map.put("account", "15381620382");
        map.put("type", "kq");
        map.put("code", "bbe57deb-1333-4626-be1f-e6a4ddfaa2b6");
        String token = jwtOperator.generateToken(map);
        System.out.println("token = " + token);
    }

    @Test
    public void sss() {
        for (int i = 0; i < 3000; i++) {
            rabbitTemplate.convertAndSend("topic.rabbit.test", "aaaa");
            rabbitTemplate.convertAndSend("topic.rabbit.test1", "bbbbb");
        }

    }

    @Test
    public void loginData() {

        String stringReg = "01F96C6C12006F0D001392003600000000010061646D696E31000000000000047863E955101400F96C6C12006F0D000000000000000000000000003031303632313131";
        String heart = "01F96C6C12006F0D00139C00240000000000000105C89346363F032310F96C6C12006F0D00000000000000000000000000";
        List<GatewayDO> list = gatewayService.list();
        list.forEach(l -> {
            String gatewayData = stringReg.replace("F96C6C12006F0D00", l.getZigbeeMac());
            String data = "2A43" + gatewayData + CmdUtils.getCmdBodySum(gatewayData) + "23";
            String heartData = heart.replace("F96C6C12006F0D00", l.getZigbeeMac());
            String heart1 = "2A31" + heartData + CmdUtils.getCmdBodySum(heartData) + "23";
            System.out.println("注册帧 = " + data);
            System.out.println("心跳帧 = " + heart1);

        });
    }

    @Test
    public void tetsxml() throws InterruptedException {
        SAXReader reader = new SAXReader();
        File file = new File("C:\\Users\\Administrator\\Desktop\\jmeter\\1.jmx");
        String stringReg = "01F96C6C12006F0D001392003600000000010061646D696E31000000000000047863E955101400F96C6C12006F0D000000000000000000000000003031303632313131";
        String heart = "01F96C6C12006F0D00139C00240000000000000105C89346363F032310F96C6C12006F0D00000000000000000000000000";
        List<GatewayDO> list = gatewayService.list();
        for (int i = 0; i < list.size(); i++) {
            String gatewayData = stringReg.replace("F96C6C12006F0D00", list.get(i).getZigbeeMac());
            String reg = "2A43" + gatewayData + CmdUtils.getCmdBodySum(gatewayData) + "23";
            String heartData = heart.replace("F96C6C12006F0D00", list.get(i).getZigbeeMac());
            String heart1 = "2A31" + heartData + CmdUtils.getCmdBodySum(heartData) + "23";
            xmlDeal(reader, "网关" + i, reg, heart1, file);
            Thread.sleep(50);
            fileCopy(file, "网关" + i);
        }

    }

    /**
     * 测试计划线程组合并
     */
    @Test
    public void mergeXml() {
        SAXReader reader = new SAXReader();
        File file = new File("C:\\Users\\Administrator\\Desktop\\jmeter\\test.jmx");
        try {
            Document document = reader.read(file.getPath());
            Element rootElement = document.getRootElement();
            //获取根元素下面的子元素
            Element hashTree = rootElement.element("hashTree");
            Element element = (Element) hashTree.content().get(3);
            List content = element.content();
            for (int i = 0; i < 200; i++) {
                Document document1 = reader.read("file:///" + "C:\\Users\\Administrator\\Desktop\\jmeter\\copy\\" + "网关" + i + ".jmx");
                Element rootElement1 = document1.getRootElement();
                Element hashTree1 = rootElement1.element("hashTree");
                for (int j = 0; j < hashTree1.nodeCount(); j++) {
                    Node node = hashTree1.node(j);
                    content.add(node);
                }
                element.setContent(content);
                FileWriter out = new FileWriter(file.getPath());
                document.write(out);
                out.flush();
                out.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void fileCopy(File file, String name) {
        File file1 = new File("C:\\Users\\Administrator\\Desktop\\jmeter\\copy\\" + name + ".jmx ");
        try {
            FileUtils.copyFile(file, file1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void xmlDeal(SAXReader reader, String name, String reg, String heart, File file) {
        try {
            Document document = reader.read(file.getPath());
            Element root = document.getRootElement();
            //获取根元素下面的子元素
            Iterator hashTree = root.elementIterator("hashTree");
            while (hashTree.hasNext()) {
                Element itemEle = (Element) hashTree.next();
                //修改控制器名称
                setThreadGroupAttribute(itemEle, file, document, name);
                //修改登陆帧(注册帧)
                setTcpSamplerRequestReg(itemEle, file, document, reg);
                //修改心跳数据帧
                setTcpSamplerRequestHeart(itemEle, file, document, heart);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * /修改名称ThreadGroup中的testname的名称(1)
     * setThreadGroupAttribute(itemEle, file, document);//修改名称
     *
     * @param itemEle
     * @param file
     * @param document
     * @throws IOException
     */
    private void setThreadGroupAttribute(Element itemEle, File file, Document document, String name) throws IOException {
        Element threadGroup = itemEle.element("ThreadGroup");

        Attribute guiclass = threadGroup.attribute("guiclass");
        guiclass.setValue("ThreadGroupGui");

        Attribute testclass = threadGroup.attribute("testclass");
        testclass.setValue("ThreadGroup");

        Attribute testname = threadGroup.attribute("testname");
        testname.setValue(name);

        Attribute enabled = threadGroup.attribute("enabled");
        enabled.setValue("true");
        List list = new ArrayList();
        list.add(guiclass);
        list.add(testclass);
        list.add(testname);
        list.add(enabled);
        threadGroup.setAttributes(list);

//                System.out.println("threadGroup = " + s);
        FileWriter out = new FileWriter(file.getPath());
        document.write(out);
        out.flush();
        out.close();

    }

    /**
     * 修改注册数据帧(2)
     *
     * @param itemEle
     * @param file
     * @param document
     */
    private void setTcpSamplerRequestReg(Element itemEle, File file, Document document, String reg) {
        Element hashTree2 = itemEle.element("hashTree");
        modifyData(hashTree2, file, document, reg);

    }

    /**
     * 修改心跳帧
     *
     * @param itemEle
     * @param file
     * @param document
     */
    private void setTcpSamplerRequestHeart(Element itemEle, File file, Document document, String heart) {
        Element hashTree2 = itemEle.element("hashTree");
        Iterator iterator3 = hashTree2.elementIterator("hashTree");
        while (iterator3.hasNext()) {
            Element element4 = (Element) iterator3.next();
            if (element4.content().size() > 0) {
                modifyData(element4, file, document, heart);
            }
        }
    }


    private void modifyData(Element hashTree2, File file, Document document, String data) {
        Iterator iterator = hashTree2.elementIterator("TCPSampler");
        try {
            while (iterator.hasNext()) {
                Element element2 = (Element) iterator.next();
                List content = element2.content();
                Element element = (Element) content.get(13);
                String TCPSamplerRequest = element.getText();
                element.setText(data);
                System.out.println("TCPSampler.request = " + TCPSamplerRequest);
                FileWriter out = new FileWriter(file.getPath());
                document.write(out);
                out.flush();
                out.close();
            }
        } catch (Exception e) {

        }
    }
}
